package com.htu.tax.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htu.tax.common.ResponseHelper;
import com.htu.tax.common.ResponseModel;
import com.htu.tax.entity.Driver;
import com.htu.tax.mapper.DriverMapper;
import com.htu.tax.payload.request.Driver.AddDriverRequest;
import com.htu.tax.payload.request.Driver.ChangeDriverRequest;
import com.htu.tax.payload.request.Driver.SelectDriverRequest;
import com.htu.tax.payload.request.Driver.UpdateDriverRequest;
import com.htu.tax.payload.base.PageRequest;
import com.htu.tax.service.DriverService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class DriverServiceImpl extends ServiceImpl<DriverMapper, Driver> implements DriverService {

    private DriverMapper driverMapper;

    public DriverServiceImpl(DriverMapper driverMapper) {
        this.driverMapper = driverMapper;
    }

    @Override
    public ResponseModel addDriver(AddDriverRequest request) {
        Snowflake snowflake = IdUtil.getSnowflake(1, 1);
        Driver driver = new Driver();
        //判断用户名是否存在
        Integer count = driverMapper.isHaveDriver(request.getName());
        if (count != 0) {
            return ResponseHelper.error("司机已存在");
        }
        driver.setName(request.getName())
                .setPhoneNumber(request.getPhoneNumber())
                .setState(1)
                .setAddTime(LocalDateTime.now())
                .setId(snowflake.nextId());
        this.save(driver);
        return ResponseHelper.buildResponseModel("添加成功");
    }

    @Override
    public IPage<Driver> selectDriver(SelectDriverRequest request) {
        IPage<Driver> DriverIPage = driverMapper.selectDriver(PageRequest.getPage(request), request.getDriverName());
        return DriverIPage;
    }

    @Override
    public void updateDriver(UpdateDriverRequest request) {
        Driver driver = this.getById(Long.valueOf(request.getId()));
        BeanUtils.copyProperties(request, driver);
        driver.setUpdateTime((LocalDateTime.now()));
        this.updateById(driver);
    }

    @Override
    public Integer changeDriverState(ChangeDriverRequest request) {
        Driver driver = this.getById(request.getId());
        Integer i = driverMapper.changeState(Long.valueOf(request.getId()));
        Integer temp = 1;
        Integer temp2 = 2;
        if (i == 1) {
            i = temp2;
        } else {
            i = temp;
        }
        driver.setState(i);
        driver.setUpdateTime(LocalDateTime.now());
        this.updateById(driver);
        return driver.getState();
    }
}
